package redis;

import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.Random;
import java.util.Set;

/**
 * @Author: 海琳琦
 * @Date: 2022/6/13 10:23
 */
public class JedisDemo1 {

    public static void main(String[] args) {
        //创建连接
        Jedis jedis = new Jedis("192.168.245.128", 6378);
        //测试
        String ping = jedis.ping();
        System.out.println(ping);
        jedis.close();
    }

    /**
     * 单元测试，操作key
     */
    @Test
    public void demo1() {
        //创建Jedis对象
        Jedis jedis = new Jedis("192.168.245.128", 6379);
        jedis.set("k1", "v1");
        jedis.set("k2", "v2");
        jedis.set("k3", "v3");
        jedis.mset("k4", "v4", "k5", "v5");
        Set<String> keys = jedis.keys("*");
        for (String s : keys) {
            System.out.println(s);
        }
        System.out.println(jedis.exists("k1"));
        System.out.println(jedis.ttl("k1"));
        System.out.println(jedis.get("k1"));
    }

    /**
     * 完成手机验证码的过程
     * 1、输入手机号-》随机生成6位数字验证码，2分钟内有效
     * 2、每个手机每天只能输入3次
     */
    @Test
    public void test() {
        String phone = "152225094861";
        verifyCode(phone);
//        getRedisCode(phone, "128942");
    }

    /**
     * 生成六位验证码
     * @return
     */
    public static String generateCode() {
        //1、生成六位验证码
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code.append(rand);
        }
        return code.toString();
    }

    public static void verifyCode(String phone) {
        //2、每个手机每天只能发送三次，验证码放到redis中，设置过期时间

        //连接redis
        Jedis jedis = new Jedis("192.168.245.128", 6379);
        //拼接key
        //手机验证码发送次数
        String countKey = "VerifyCode" + phone + ":count";
        //验证码key
        String codeKey = "VerifyCode" + phone + ":code";

        //每个手机每天只能发送三次
        String count = jedis.get(countKey);
        if (count == null) {
            //还没有发送验证码
            //设置发送次数为1
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.valueOf(count) <= 2) {
            jedis.incr(countKey);
        }else{
            //发送次数>=3，此时不能再发送
            System.out.println("发送次数超限");
            jedis.close();
            return;
        }

        //发送的验证码放到redis中
        String verifyCode = generateCode();
        jedis.setex(codeKey, 120, verifyCode);
        jedis.close();
    }

    /**
     * 验证验证码是否正确
     * @param phone
     * @param code
     */
    public static void getRedisCode(String phone, String code) {
        Jedis jedis = new Jedis("192.168.245.128", 6379);
        //手机验证码发送次数
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);
        if (code.equals(redisCode)) {
            System.out.println("ok");
        }else{
            System.out.println("no");
        }
        jedis.close();
    }
}
